#include "camerasettingwid.h"
#include "ui_camerasettingwid.h"
#include "paramadddialog.h"

CameraSettingWid::CameraSettingWid(QWidget* parent)
	: QWidget(parent)
	, ui(new Ui::CameraSettingWid())
{
	ui->setupUi(this);
	//setStyleSheet("font: 12pt \"Agency FB\"");
	Init();
}

CameraSettingWid::~CameraSettingWid()
{
	delete ui;
}

void CameraSettingWid::Init()
{
	auto cfg = cfgrw->GetCameraCfg();
	if (!cfg.visPath().isEmpty()) {
		ui->lineEdit->setText(cfg.visPath());
	}
	if (!cfg.picpath().isEmpty()) {
		ui->lineEdit_2->setText(cfg.picpath());
	}
	ui->tabWidget->clear();
	for (auto& iter : cfg.cameras()) {
		auto temp = new CameraConfig();
		temp->SetCfg(iter);
		ui->tabWidget->addTab(temp, iter.id());
	}
}

void CameraSettingWid::on_pushButton_clicked()  // 新增
{
	QStringList param;
	param << "编号：";
	ParamAddDialog dlg(param, this);
	dlg.exec();
	auto str = dlg.GetParam();
	if (str.size() > 0) {
		CameraCfg cfg = {};
		cfg.id = str.at(0);
		auto temp = new CameraConfig();
		temp->SetCfg(cfg);
		ui->tabWidget->addTab(temp, cfg.id());
	}
}
void CameraSettingWid::on_pushButton_2_clicked()	// 删除
{
	CameraConfig* tmp = qobject_cast<CameraConfig*>(ui->tabWidget->currentWidget());
	if (tmp == nullptr) {
		ui->tabWidget->removeTab(ui->tabWidget->currentIndex());
		return;
	}
	auto cfg = tmp->GetCfg();
	auto ret = QMessageBox::question(this, "QUESTION", QString("确认删除%1, 删除后数据无法恢复").arg(cfg.id()));
	if (ret == QMessageBox::StandardButton::Yes) {
		ui->tabWidget->removeTab(ui->tabWidget->currentIndex());
		tmp->deleteLater();
	}
}
void CameraSettingWid::on_pushButton_3_clicked()	// 保存
{
	VisualJ cfg = {};
	cfg.visPath() = ui->lineEdit->text();
	if (cfg.visPath().isEmpty()) {
		QMessageBox::warning(this, "警告", "视觉服务地址为空");
	}
	cfg.picpath() = ui->lineEdit_2->text();
	if (cfg.picpath().isEmpty()) {
		QMessageBox::warning(this, "警告", "图片保存路径为空");
	}
	for (int i = 0; i < ui->tabWidget->count(); i++) {
		CameraConfig* tmp = qobject_cast<CameraConfig*>(ui->tabWidget->widget(i));
		if (tmp == nullptr) {
			ui->tabWidget->removeTab(i);
			continue;
		}
		cfg.cameras().append(tmp->GetCfg());
	}
	if (!cfgrw->UpdateCameraCfg(cfg)) {
		QMessageBox::warning(this, "警告", "相机配置保存失败");
		return;
	}
	Init();
}


